package com.xuetang9.BBS.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.xuetang9.BBS.dao.SectionDao;
import com.xuetang9.BBS.domain.Section;

@Repository
public class SectionDaoImpl implements SectionDao{


	@Autowired
	private JdbcTemplate jdbcTemplate;

	private RowMapper<Section> getSectionRowMapper() {
		return new RowMapper<Section>() {

			@Override
			public Section mapRow(ResultSet resultSet, int arg1) throws SQLException {
			
				Section section = new Section();
				section.setDescription(resultSet.getString("description"));
				section.setImgUrl(resultSet.getString("imgUrl"));
				section.setPid(resultSet.getString("pid"));
				section.setSid(resultSet.getString("sid"));
				section.setTitle(resultSet.getString("title"));
				return section;
			}
			
			
		};
	}

	@Override
	public List<Section> findSectionByPid(String pid) {
		String sql = "select * from section where pid = ?";
		RowMapper<Section> rm = getSectionRowMapper();
		return jdbcTemplate.query(sql, rm, pid);
		
	}
	
	@Override
	public List<Section> selectChildrenSections() {
		String sql = "select * from section where pid <> 0";
		RowMapper<Section> rm = getSectionRowMapper();
		return jdbcTemplate.query(sql, rm);
	}

	@Override
	public int insertSection(Section section) {
		String sql = "insert into section values(default,?,?,?,?)";
		return jdbcTemplate.update(sql,section.getTitle(),section.getDescription(),section.getPid(),section.getImgUrl());
	}
	
	
}	
